<?php
    class ServiceController extends Controller
    {
        public function direct(){
            if(!isset($_SESSION["userId"])){
                $this->redirect(Url::createUrl("login/index"));
            }           
        }  
        public function actionIndex(){
            $this->direct();
            $this->metaTitle = "mTop - Mạng kiếm tiền trực tuyến.";
            $this->metaKeywords = "Bán game, Bán ứng dụng, Bán SMS Kute, Bán hotclip, Gắn kích hoạt apk, Gắn kích hoạt java ,  Kinh doanh sms";
            $this->metaDescription = "Mạng kiếm tiền online của Wapmaster - Kinh doanh SMS  Content - Kinh doanh Game và Ứng dụng.";
            $this->render("index");
        }
        public function actionAppList(){
            $this->direct();
            $month = date("m",time());
            $year =    date("Y",time());
            $currentPage = isset($_GET["page"]) ? intval($_GET["page"]) : 1;
            $order = isset($_GET["t"]) ? intval($_GET["t"]) : "";
            $currentPage = $currentPage==0 ? 1 : $currentPage;
            $numberRecordPerPage = 5;

            if($order=="0"){
                $data_app = App::getOtherApp($currentPage, $numberRecordPerPage);
            }else{
                $data_app = App::getOtherAppHot($currentPage, $numberRecordPerPage); 
            }
            $totalApp = App::getTotalApp();
            $numberPage =  ceil($totalApp / $numberRecordPerPage);

            $this->render("application_list",array("data_app"=>$data_app,"numberPage"=>$numberPage,"currentPage"=>$currentPage,"order"=>$order)) ;
        } 
        public function actionGameOnlineList(){
            $this->direct();
            $month = date("m",time());
            $year =    date("Y",time());
            $currentPage = isset($_GET["page"]) ? intval($_GET["page"]) : 1;
            $order = isset($_GET["t"]) ? intval($_GET["t"]) : 0; 
            if($order>1){
                $order=1;
            } 
            $currentPage = $currentPage==0 ? 1 : $currentPage;
            $numberRecordPerPage = 5;
            if($order==0){
                $data_app = Game::getGameOnline($currentPage, $numberRecordPerPage); 
            }else{
                $data_app = Game::getGameOnlineHot($currentPage, $numberRecordPerPage); 
            }

            $totalGameOnline = Game::getTotalGameOnline();
            $numberPage =  ceil($totalGameOnline / $numberRecordPerPage);

            $this->render("application_list",array("data_app"=>$data_app,"numberPage"=>$numberPage,"currentPage"=>$currentPage,"order"=>$order)) ;
        }
        public function actionGameOfflineList(){
            $this->direct();
            $month = date("m",time());
            $year =    date("Y",time());
            $currentPage = isset($_GET["page"]) ? intval($_GET["page"]) : 1;
            $order = isset($_GET["t"]) ? intval($_GET["t"]) : 0; 
            if($order>1){
                $order=1;
            } 
            $currentPage = $currentPage==0 ? 1 : $currentPage;
            $numberRecordPerPage = 5;
            if($order==0){
                $data_app = Game::getGameOffline($currentPage, $numberRecordPerPage);
            }else{
                $data_app = Game::getGameOfflineHot($currentPage, $numberRecordPerPage); 
            }
            $totalGameOffline = Game::getTotalGameOffline();
            $numberPage =  ceil($totalGameOffline / $numberRecordPerPage);

            $this->render("application_list",array("data_app"=>$data_app,"numberPage"=>$numberPage,"currentPage"=>$currentPage,"order"=>$order)) ;
        }
        public function actionApplicationDetail()
        {
            $this->direct();
            $error="";
            $check = Chat::checkUserBann($_SESSION["userId"]);        
            $month = date("m",time());
            $year =    date("Y",time());  
            $username = $_SESSION["username"];
            $id = isset($_GET["id"]) ? intval($_GET["id"]) : 0;
            $type = isset($_GET["type"]) ? intval($_GET["type"]) : 1; 
            if(empty($id) || empty($type) ) {
                throw new CHttpException(404, "Trang yêu cầu không tồn tại");
            } 
            if($type==1){
                $data_detail =  Game::getInfoGame($id);
            }   else {
                $data_detail = App::getInfoApp($id) ; 
            }

            if(isset($_POST["content"])&& $check['bann_chat']==0 && strlen($_POST["content"])>1022){
                $error .= "Bạn không được chat quá 1024 ký tự";
            } else if(isset($_POST["content"]) && $check['bann_chat']=="0"){
                    $data = array();
                    $data["userId"] = $_SESSION["userId"];
                    $data["username"] = $_SESSION["username"];
                    $data["content"] = trim($_POST["content"]);
                    $data["content"] =Common::bbcode_format($data["content"]);
                    $data["type"] = $type;
                    $data["appId"] = $id;
                    $data["create_date"] = time() - 1;
                    if(!empty($data["content"])){
                        $result = Chat::InsertChat($data);
                    }

                    $this->redirect(Url::createUrl("service/applicationDetail",array("alias"=>$data_detail['alias'],"id"=>$id,"type"=>$type)));
            } else if(isset($_POST["content"]) && $check['bann_chat']==1 && $time_now > $check['from_date'] && $time_now < $check['to_date']){
                    $error .= "Bạn đang bị ban chat";                
                } 
                $currentPage = isset($_GET["page"]) ? intval($_GET["page"]) : 1;
            $currentPage = $currentPage==0 ? 1 : $currentPage;
            $numberRecordPerPage =10 ;

            if($type==1){
                $chat = Chat::getChat($currentPage, $numberRecordPerPage,1,$id);
                $totalChat = Chat::getTotalChat(1,$id);
                $numberPage = ceil($totalChat / $numberRecordPerPage);
            } else{   
                $chat = Chat::getChat($currentPage, $numberRecordPerPage,2,$id);
                $totalChat = Chat::getTotalChat(2,$id);
                $numberPage = ceil($totalChat / $numberRecordPerPage);
            }  
            $this->render("application_detail",array("data_detail"=>$data_detail,"type"=>$type,"chat"=>$chat,"numberPage"=>$numberPage,"currentPage"=>$currentPage,"id"=>$id));   
        }
        public function actionReview(){
            $this->direct();        
            $month = date("m",time());
            $year =    date("Y",time());  
            $id = isset($_GET["id"]) ? intval($_GET["id"]) : 0;
            $type = isset($_GET["type"]) ? intval($_GET["type"]) : 1; 
            if(empty($id) || empty($type) ) {
                throw new CHttpException(404, "Trang yêu cầu không tồn tại");
            } 
            if($type==1){
                $data_detail =  Game::getInfoGame($id);
                $data_rate =  Rate::getDataByMonthAndYearAndType($month,$year,1);
            } else{
                $data_detail = App::getInfoApp($id) ;
                $data_rate =  Rate::getDataByMonthAndYearAndType($month,$year,2);
            } 
            $this->render("review",array("data_detail"=>$data_detail, "data_rate"=>$data_rate,"type"=>$type));  
        }
        public function actionAttachPaymentJarOption(){
            $this->direct();
            $upload_type =isset($_POST['upload_type'])? intval($_POST['upload_type']):0;
            $error = "";     
            $this->render("attachPaymentOption",array("error"=>$error,"upload_type"=>$upload_type));
        }
        public function actionUploadFileJar(){
            $this->direct();
            $error = "";
            $time=time();
            $status=1; 
            $isConfirm=0;  
            //$serviceNumber="8755";
            $mo = "TJGAME";
            $username=$_SESSION['username'];
            $userId=$_SESSION['userId'];
            $refCode=User::getRefCode($userId);
            $refCode=$refCode['refCode']; 
            $price=isset($_POST['price'])? intval($_POST['price']): 15000; 
            $timeTrail=isset($_POST['timeTrail'])? intval($_POST['timeTrail']): 30;
            $countTrail=isset($_POST['countTrail'])? intval($_POST['countTrail']) : 1;
            $timeSms=isset($_POST['timeSms'])? intval($_POST['timeSms']) : 1;  
            $countSms=isset($_POST['countSms'])? intval($_POST['countSms']) : 1;  
            $isSms = isset($_POST['isSms'])  ? 1 : 0;
            $isPriceDown = isset($_POST['isPriceDown'])  ? 1 : 0;   
            $upload_type =isset($_POST['upload_type'])? intval($_POST['upload_type']):0;
            $totalfile =isset($_POST['totalfile'])?intval($_POST['totalfile']): 1;


            $timeSms=$timeSms*86400;
            $serviceNumber= "8x55";
            if($price == 5000){
            $serviceNumber=str_replace("x","5",$serviceNumber);
            }else if($price == 10000){
            $serviceNumber=str_replace("x","6",$serviceNumber);
            }else if($price == 15000){
            $serviceNumber=str_replace("x","7",$serviceNumber);
            }

            $config = "\"price=".$price."&timeTrail=".$timeTrail."&countTrail=".$countTrail."&countSms=".$countSms."&timeSms=".$timeSms."&isSms=".$isSms."&isConfirm=".$isConfirm."&mo=".$mo."&serviceNumber=".$serviceNumber."&\"";
            $location = getcwd();
            $upload_path = $location . "/upload/modgame/".$username."/modjar/".date("Y/md",time())."/"; 

            $allowed_filetypes = array('jar','jad');
            $max_filesize = 25242880; 
            if(isset($_FILES['userfile']['name'])){ 
                $count=count($_FILES['userfile']['name']);
                if($count==1 && $_FILES['userfile']['name'][0]=='') {
                    $error.="<p style='color: red'>- Bạn chưa nhập file cần upload </p>";
                }
                for($i=0;$i<$totalfile;$i++){
                    if(isset($_FILES['userfile']['name'][$i])&& $_FILES['userfile']['name'][$i]!=""){

                        $filename[$i] = $_FILES['userfile']['name'][$i]; 
                        $filename[$i]=StringUtils::RemoveSign($filename[$i]);
                        $filename[$i]=str_replace (" ", "_", $filename[$i]);
                        $arr[$i]=explode(".",$filename[$i]);
                        $key=count($arr[$i]);
                        if(!in_array($arr[$i][$key-1],$allowed_filetypes)){
                            $error.="<p style='color: red'>- Bạn phải upload đúng định định dạng file jar,jad </p>";break;
                        }
                        if(filesize($_FILES['userfile']['tmp_name'][$i]) > $max_filesize){
                            $error.="<p style='color: red'>- File bạn upload có kích thước lớn hơn 25MB </p>";  break; 
                        } 
                        if($arr[$i][$key-1]=="jad") {
                            $content=file_get_contents($_FILES['userfile']['tmp_name'][$i]);
                            preg_match('/MIDlet-Jar-URL:(.*?)jar/si',$content,$match);
                            $out=isset($match[1]) ? trim($match[1]).'jar':'';

                            if(!preg_match('/http/si',$out)){
                                $error.="<p style='color: red'>- Không tìm thấy đường dẫn file jar </p>";break;
                            }else{
                                $link_url[$i]=$out;
                                $filename[$i]=basename($link_url[$i]);
                                $arr[$i]=explode(".",$filename[$i]);
                                if(count($arr[$i])>2){
                                    $count=count($arr[$i]);
                                    $filename_jad[$i]=$arr[$i][0];
                                    for($j=1;$j<$count;$j++){
                                        $filename_jad[$i].=".".$arr[$i][$j];
                                    }
                                } else{
                                    $filename_jad[$i]=$arr[$i][0].".jad"; 
                                }
                            } 
                        }
                        $code =isset($_POST["code"])? trim(strip_tags($_POST["code"])):"";
                        $code_security = isset($_SESSION["code_security"]) ? $_SESSION["code_security"] : "";
                        if(empty($code)){
                            $error .= "<p style='color: red'>- Bạn chưa nhập mã xác nhận</p>";break;
                        } 
                        if($code!=$code_security) {
                            $error .= "<p style='color: red'>- Bạn nhập mã xác thực không đúng</p>" ;break;
                        }
                        if(isset($link_url[$i])){

                            $data['file']=file_get_contents($_FILES['userfile']['tmp_name'][$i]);
                            $data["username"] = $username;
                            $data["filename"] = $filename_jad[$i];
                            $result = Common::saveFileTmp($data,$upload_path);

                            if($result==1){
                                $link_down_jad[$i]= Yii::app()->params['base_url'].'/upload/modgame/'.$_SESSION['username'].'/modjar/'.date("Y/md",$time).'/'.$filename_jad[$i];
                                $data["username"] = $username;
                                $data["link_url"] = $link_url[$i];
                                $data["filename"] = $filename[$i];
                                $result = Common::saveLink($data,$upload_path);
                                $link_down[$i]= Yii::app()->params['base_url'].'/upload/modgame/'.$_SESSION['username'].'/modjar/'.date("Y/md",$time).'/'.$filename[$i]; 
                                $url_short[$i] = Common::bitly_shorten($link_down[$i]);
                                $url_short_jad[$i] = Common::bitly_shorten($link_down_jad[$i]);
                                exec('java -jar '.$location.'/kichhoat_java/kichhoat.jar '.$upload_path.$filename[$i].' '.$upload_path.' '.$refCode.' '.$config,$output,$result);
                                $lastId=AttachPaymentJar::InsertFileJar($username,$userId,$filename[$i],$serviceNumber,$mo,$price,$timeTrail,$countTrail,$timeSms,$countSms,$isSms,$isPriceDown,$status,time());

                            }  
                        } 
                        else
                        {   
                            $data['file']=file_get_contents($_FILES['userfile']['tmp_name'][$i]);
                            $data["username"] = $username;
                            $data["filename"] = $filename[$i];
                            $result = Common::saveFileTmp($data,$upload_path);
                            if($result==1){
                                $link_down[$i]=Yii::app()->params['base_url'].'/upload/modgame/'.$_SESSION['username'].'/modjar/'.date("Y/md",$time).'/'.$filename[$i];
                                $url_short[$i] = Common::bitly_shorten($link_down[$i]);
                                @exec('java -jar '.$location.'/kichhoat_java/kichhoat.jar '.$upload_path.$filename[$i].' '.$upload_path.' '.$refCode.' '.$config,$output,$result);
                                //var_dump($output,$result);
                                //var_dump('java -jar '.$location.'/kichhoat_java/kichhoat.jar '.$upload_path.$filename[$i].' '.$upload_path.' '.$refCode.' '.$config);die;
                                $lastId=AttachPaymentJar::InsertFileJar($username,$userId,$filename[$i],$serviceNumber,$mo,$price,$timeTrail,$countTrail,$timeSms,$countSms,$isSms,$isPriceDown,$status,time());
                            }
                        }
                    }
                }
                if(empty($error)){
                    $this->redirect(Url::createUrl("service/gameModListJar"));
                } 
            }
            $this->render(
            "upload_file"
            ,array(
            "error"=>$error
            ,"timeTrail"=>$timeTrail
            ,"price"=>$price
            ,"countTrail"=>$countTrail
            ,"timeSms"=>$timeSms
            ,"countSms"=>$countSms
            ,"isSms"=>$isSms
            ,"isPriceDown"=>$isPriceDown
            ,"upload_type"=>$upload_type
            ,"totalfile"=>$totalfile 
            )
            );  
        }
        public function actionUploadLinkJar(){
            $error="";
            $status=1;
            $isConfirm=0;
            //$serviceNumber="8755";
            $mo = "TJGAME";
            $username=$_SESSION['username'];
            $userId=$_SESSION['userId'];
            $refCode=User::getRefCode($userId);
            $refCode=$refCode['refCode'];
            $price=isset($_POST['price'])? intval($_POST['price']): 15000; 
            $timeTrail=isset($_POST['timeTrail'])? intval($_POST['timeTrail']): 30;
            $countTrail=isset($_POST['countTrail'])? intval($_POST['countTrail']) : 1;
            $timeSms=isset($_POST['timeSms'])? intval($_POST['timeSms']) : 1;  
            $countSms=isset($_POST['countSms'])? intval($_POST['countSms']) : 1;  
            $isSms = isset($_POST['isSms'])  ? 1 : 0;
            $isPriceDown = isset($_POST['isPriceDown'])  ? 1 : 0;   
            $upload_type =isset($_POST['upload_type'])? intval($_POST['upload_type']):0;
            $totalfile =isset($_POST['totalfile'])?intval($_POST['totalfile']): 1;

            $timeSms=$timeSms*86400;

            $serviceNumber= "8x55";
            if($price == 5000){
            $serviceNumber=str_replace("x","5",$serviceNumber);
            }else if($price == 10000){
            $serviceNumber=str_replace("x","6",$serviceNumber);
            }else if($price == 15000){
            $serviceNumber=str_replace("x","7",$serviceNumber);
            }

            $config = "\"price=".$price."&timeTrail=".$timeTrail."&countTrail=".$countTrail."&countSms=".$countSms."&timeSms=".$timeSms."&isSms=".$isSms."&isConfirm=".$isConfirm."&mo=".$mo."&serviceNumber=".$serviceNumber."&\"";

            $location = getcwd();
            $upload_path = $location . "/upload/modgame/".$username."/modjar/".date("Y/md",time())."/";
            if(isset($_POST['link'])){
                for($i=0;$i<$totalfile;$i++){
                    if(isset($_POST['link'][$i]) && $_POST['link'][$i] !="" ){
                        $link_url[$i]=$_POST['link'][$i];
                        $regx = "/^http:\/\/(.*)/si";
                        if($link_url[$i]==preg_match($regx, $link_url[$i])){
                            $error .=  "Link nhập vào phải có http://";   break; 
                        }

                        $filename[$i]=basename($link_url[$i]);
                        $ext[$i]=explode(".",$filename[$i]);
                        $count=count($ext[$i]);
                        if(!in_array("jar",$ext[$i])&&!in_array("jad",$ext[$i])){
                            $error.="<p style='color: red'>- File upload phải có đuôi jar,jad </p>";
                            break;
                        }
                        if($ext[$i][$count-1]=="jad") {
                            $content=Common::cUrl($link_url[$i]);
                            preg_match('/MIDlet-Jar-URL:(.*?)jar/si',$content,$match);
                            $out=isset($match[1]) ? trim($match[1]).'jar':'';
                            if(!preg_match('/http/si',$out)){
                                $error.="<p style='color: red'>- Không tìm thấy đường dẫn file jar </p>";break;
                            }
                            else{  
                                $data["username"] = $username;
                                $data["link_url"] = $link_url[$i];

                                $link_url[$i]=$out; 
                                $filename[$i]=basename($link_url[$i]); 
                                $arr[$i]=explode(".",$filename[$i]);  
                                if(count($arr[$i])>2){
                                    $count=count($arr[$i]);
                                    $filename_jad[$i]=$arr[$i][0];
                                    for($j=1;$j<$count;$j++){
                                        $filename_jad[$i].=".".$arr[$i][$j];
                                    }
                                } else{
                                    $filename_jad[$i]=$arr[$i][0].".jad"; 
                                }
                                $data["filename"] = $filename_jad[$i];

                                $result= Common::saveFile($data,$upload_path);

                                $link_down_jad[$i]= Yii::app()->params['base_url'].'/upload/modgame/'.$_SESSION['username'].'/modjar/'.date("Y/md",time()).'/'.$filename_jad[$i];
                                $url_short_jad[$i] = Common::bitly_shorten($link_down_jad[$i]);
                            } 
                        }
                        /* check catpcha */
                        $code =isset($_POST["code"])? trim(strip_tags($_POST["code"])):"";
                        $code_security = isset($_SESSION["code_security"]) ? $_SESSION["code_security"] : "";
                        if(empty($code)){
                            $error .= "<p style='color: red'>- Bạn chưa nhập mã xác nhận</p>";break;
                        } 
                        if($code!=$code_security) {
                            $error .= "<p style='color: red'>- Bạn nhập mã xác thực không đúng</p>" ;break;
                        }

                        $data["username"] = $username;
                        $data["link_url"] = $link_url[$i];
                        $data["filename"] = $filename[$i];
                        $result = Common::saveLink($data,$upload_path);
                        $link_down[$i]= Yii::app()->params['base_url'].'/upload/modgame/'.$_SESSION['username'].'/modjar/'.date("Y/md",time()).'/'.$filename[$i];
                        $url_short[$i] = Common::bitly_shorten($link_down[$i]);
                        exec('java -jar '.$location.'/kichhoat_java/kichhoat.jar '.$upload_path.$filename[$i].' '.$upload_path.' '.$refCode.' '.$config,$output,$result);                       
                        $lastId=AttachPaymentJar::InsertFileJar($username,$userId,$filename[$i],$serviceNumber,$mo,$price,$timeTrail,$countTrail,$timeSms,$countSms,$isSms,$isPriceDown,$status,time());
                    } 
                }
                if(empty($error)){
                    $this->redirect(Url::createUrl("service/gameModListJar"));
                } 

            }
            $this->render(
            "upload_file"
            ,array(
            "error"=>$error
            ,"timeTrail"=>$timeTrail
            ,"price"=>$price
            ,"countTrail"=>$countTrail
            ,"timeSms"=>$timeSms
            ,"countSms"=>$countSms
            ,"isSms"=>$isSms
            ,"isPriceDown"=>$isPriceDown
            ,"upload_type"=>$upload_type
            ,"totalfile"=>$totalfile 
            )
            );
        }
        public function actionGameModListJar(){
            $this->direct();
            $userId = $_SESSION['userId'];

            $currentPage = isset($_GET["page"]) ? intval($_GET["page"]) : 1;
            $currentPage = $currentPage==0 ? 1 : $currentPage;
            $numberRecordPerPage = 20; 

            $totalGameKHJar = AttachPaymentJar::getTotalGameKHJar($userId);
            $numberPage = ceil($totalGameKHJar/$numberRecordPerPage);

            $data = AttachPaymentJar::getDataByUserIdJar($userId,$currentPage,$numberRecordPerPage)  ;
            $url = Url::createUrl("service/gameModListJar");
            $url1 = rtrim($url,"/");
            $url.='/';
            $paging = Paging::show_paging_wap_user($numberPage,$currentPage,$url,$url1);
            $this->render("gamemod_list",array("data"=>$data,"paging"=>$paging));
        }
        public function actionGameModDetailJar(){
            $this->direct();
            $userId = $_SESSION['userId'];
            $id = isset($_GET['id'])? intval($_GET['id']) : 0 ; 
            $data = AttachPaymentJar::getDataByGameIdJar($id)  ;
            if(empty($data) || $id==0) {
                $this->render("error");
            }else{
                $this->render("gamemod_detail",array("data"=>$data)); 
            }
        }
        public function actionAttachPaymentApkOption(){
            $this->direct();
            $upload_type =isset($_POST['upload_type'])? intval($_POST['upload_type']):0;
            $error = "";     
            $this->render("attachPaymentOptionApk",array("error"=>$error,"upload_type"=>$upload_type));
        }
        public function actionUploadFileApk(){
            $this->direct();
            $error = "";
            $time=time();
            $status=0;   
            //$serviceNumber="8755";
            $mo = "TKGAME";
            $username=$_SESSION['username'];
            $userId=$_SESSION['userId'];
            $refCode=User::getRefCode($userId);
            $refCode=$refCode['refCode']; 
            $price=isset($_POST['price'])? intval($_POST['price']): 15000; 
            $timeTrail=isset($_POST['timeTrail'])? intval($_POST['timeTrail']): 30;
            $countTrail=isset($_POST['countTrail'])? intval($_POST['countTrail']) : 1;
            $timeSms=isset($_POST['timeSms'])? intval($_POST['timeSms']) : 1;  
            $countSms=isset($_POST['countSms'])? intval($_POST['countSms']) : 1;  
            $isSms = isset($_POST['isSms'])  ? 1 : 0;
            $isPriceDown = isset($_POST['isPriceDown'])  ? 1 : 0;   
            $upload_type =isset($_POST['upload_type'])? intval($_POST['upload_type']):0;
            $totalfile =isset($_POST['totalfile'])?intval($_POST['totalfile']): 1;
            
            $serviceNumber= "8x55";
            if($price == 5000){
            $serviceNumber=str_replace("x","5",$serviceNumber);
            }else if($price == 10000){
            $serviceNumber=str_replace("x","6",$serviceNumber);
            }else if($price == 15000){
            $serviceNumber=str_replace("x","7",$serviceNumber);
            }
            
            $location = getcwd();
            $upload_path = $location . "/upload/modgame/".$username."/modapk/".date("Y/md",time())."/"; 

            $allowed_filetypes = array('apk');
            $max_filesize = 100242880; 
            if(isset($_FILES['userfile']['name'])){ 
                $count=count($_FILES['userfile']['name']);
                if($count==1 && $_FILES['userfile']['name'][0]=='') {
                    $error.="<p style='color: red'>- Bạn chưa nhập file cần upload </p>";
                }
                for($i=0;$i<$totalfile;$i++){
                    if(isset($_FILES['userfile']['name'][$i])&& $_FILES['userfile']['name'][$i]!=""){

                        $filename[$i] = $_FILES['userfile']['name'][$i]; 
                        $filename[$i]=StringUtils::RemoveSign($filename[$i]);
                        $filename[$i]=str_replace (" ", "_", $filename[$i]);
                        $arr[$i]=explode(".",$filename[$i]);
                        $key=count($arr[$i]);
                        if(!in_array($arr[$i][$key-1],$allowed_filetypes)){
                            $error.="<p style='color: red'>- Bạn phải upload đúng định định dạng file apk </p>";break;
                        }
                        if(filesize($_FILES['userfile']['tmp_name'][$i]) > $max_filesize){
                            $error.="<p style='color: red'>- File bạn upload có kích thước lớn hơn 100MB </p>";  break; 
                        } 

                        $code =isset($_POST["code"])? trim(strip_tags($_POST["code"])):"";
                        $code_security = isset($_SESSION["code_security"]) ? $_SESSION["code_security"] : "";
                        if(empty($code)){
                            $error .= "<p style='color: red'>- Bạn chưa nhập mã xác nhận</p>";break;
                        } 
                        if($code!=$code_security) {
                            $error .= "<p style='color: red'>- Bạn nhập mã xác thực không đúng</p>" ;break;
                        }


                        $data['file']=file_get_contents($_FILES['userfile']['tmp_name'][$i]);
                        $data["username"] = $username;
                        $data["filename"] = $filename[$i];
                        $result = Common::saveFileTmp($data,$upload_path);
                        if($result==1){
                            $link_down[$i]=Yii::app()->params['base_url'].'/upload/modgame/'.$_SESSION['username'].'/modapk/'.date("Y/md",$time).'/'.$filename[$i];
                            $url_short[$i] = Common::bitly_shorten($link_down[$i]);
                            $lastId=AttachPaymentApk::InsertFileApk($username,$refCode,$userId,$filename[$i],$serviceNumber,$mo,$price,$timeTrail,$countTrail,$timeSms,$countSms,$isSms,$isPriceDown,$status,time());
                        }

                    }
                }
                if(empty($error)){
                    $this->redirect(Url::createUrl("service/gameModListApk"));
                } 
            }
            $this->render(
            "upload_file_apk"
            ,array(
            "error"=>$error
            ,"timeTrail"=>$timeTrail
            ,"price"=>$price
            ,"countTrail"=>$countTrail
            ,"timeSms"=>$timeSms
            ,"countSms"=>$countSms
            ,"isSms"=>$isSms
            ,"isPriceDown"=>$isPriceDown
            ,"upload_type"=>$upload_type
            ,"totalfile"=>$totalfile 
            )
            );  
        }
        public function actionUploadLinkApk(){
            $error="";
            $status=0;
            //$serviceNumber="8755";
            $mo = "TKGAME";
            $username=$_SESSION['username'];
            $userId=$_SESSION['userId'];
            $refCode=User::getRefCode($userId);
            $refCode=$refCode['refCode'];
            $price=isset($_POST['price'])? intval($_POST['price']): 15000; 
            $timeTrail=isset($_POST['timeTrail'])? intval($_POST['timeTrail']): 30;
            $countTrail=isset($_POST['countTrail'])? intval($_POST['countTrail']) : 1;
            $timeSms=isset($_POST['timeSms'])? intval($_POST['timeSms']) : 1;  
            $countSms=isset($_POST['countSms'])? intval($_POST['countSms']) : 1;  
            $isSms = isset($_POST['isSms'])  ? 1 : 0;
            $isPriceDown = isset($_POST['isPriceDown'])  ? 1 : 0;   
            $upload_type =isset($_POST['upload_type'])? intval($_POST['upload_type']):0;
            $totalfile =isset($_POST['totalfile'])?intval($_POST['totalfile']): 1;
            
            $serviceNumber= "8x55";
            if($price == 5000){
            $serviceNumber=str_replace("x","5",$serviceNumber);
            }else if($price == 10000){
            $serviceNumber=str_replace("x","6",$serviceNumber);
            }else if($price == 15000){
            $serviceNumber=str_replace("x","7",$serviceNumber);
            }
            
            $location = getcwd();
            $upload_path = $location . "/upload/modgame/".$username."/modapk/".date("Y/md",time())."/";
            if(isset($_POST['link'])){
                for($i=0;$i<$totalfile;$i++){
                    if(isset($_POST['link'][$i]) && $_POST['link'][$i] !="" ){
                        $link_url[$i]=$_POST['link'][$i];
                        $regx = "/^http:\/\/(.*)/si";
                        if($link_url[$i]==preg_match($regx, $link_url[$i])){
                            $error .=  "Link nhập vào phải có http://";   break; 
                        }

                        $filename[$i]=basename($link_url[$i]);
                        $ext[$i]=explode(".",$filename[$i]);
                        $count=count($ext[$i]);
                        if(!in_array("apk",$ext[$i])){
                            $error.="<p style='color: red'>- File upload phải có đuôi apk </p>";
                            break;
                        }

                        /* check catpcha */
                        $code =isset($_POST["code"])? trim(strip_tags($_POST["code"])):"";
                        $code_security = isset($_SESSION["code_security"]) ? $_SESSION["code_security"] : "";
                        if(empty($code)){
                            $error .= "<p style='color: red'>- Bạn chưa nhập mã xác nhận</p>";break;
                        } 
                        if($code!=$code_security) {
                            $error .= "<p style='color: red'>- Bạn nhập mã xác thực không đúng</p>" ;break;
                        }

                        $data["username"] = $username;
                        $data["link_url"] = $link_url[$i];
                        $data["filename"] = $filename[$i];
                        $result = Common::saveLink($data,$upload_path);
                        $link_down[$i]= Yii::app()->params['base_url'].'/upload/modgame/'.$_SESSION['username'].'/modapk/'.date("Y/md",time()).'/'.$filename[$i];
                        $url_short[$i] = Common::bitly_shorten($link_down[$i]);
                        $lastId=AttachPaymentApk::InsertFileApk($username,$refCode,$userId,$filename[$i],$serviceNumber,$mo,$price,$timeTrail,$countTrail,$timeSms,$countSms,$isSms,$isPriceDown,$status,time());
                    } 
                }
                if(empty($error)){
                    $this->redirect(Url::createUrl("service/gameModListApk"));
                } 

            }
            $this->render(
            "upload_file_apk"
            ,array(
            "error"=>$error
            ,"timeTrail"=>$timeTrail
            ,"price"=>$price
            ,"countTrail"=>$countTrail
            ,"timeSms"=>$timeSms
            ,"countSms"=>$countSms
            ,"isSms"=>$isSms
            ,"isPriceDown"=>$isPriceDown
            ,"upload_type"=>$upload_type
            ,"totalfile"=>$totalfile 
            )
            );
        }
        public function actionGameModListApk(){
            $this->direct();
            $userId = $_SESSION['userId'];

            $currentPage = isset($_GET["page"]) ? intval($_GET["page"]) : 1;
            $currentPage = $currentPage==0 ? 1 : $currentPage;
            $numberRecordPerPage = 20; 

            $totalGameKHApk = AttachPaymentApk::getTotalGameKHApk($userId);
            $numberPage = ceil($totalGameKHApk/$numberRecordPerPage);


            $data = AttachPaymentApk::getDataByUserIdApk($userId,$currentPage,$numberRecordPerPage)  ;
            $url = Url::createUrl("service/gameModListApk");
            $url1 = rtrim($url,"/");
            $url.='/';
            $paging = Paging::show_paging_wap_user($numberPage,$currentPage,$url,$url1);
            $this->render("gamemod_list_apk",array("data"=>$data,'paging'=>$paging));
        }
        public function actionGameModDetailApk(){
            $this->direct();
            $userId = $_SESSION['userId'];
            $id = isset($_GET['id'])? intval($_GET['id']) : 0 ; 
            $data = AttachPaymentApk::getDataByGameIdApk($id)  ;
            if(empty($data) || $id==0) {
                $this->render("error");
            }else{
                $this->render("gamemod_detail_apk",array("data"=>$data)); 
            }
        }
        public function actionAjaxDelete(){
            $time_now = time();
            $id = isset($_POST["id"]) ? intval($_POST["id"]):0;
            $type = isset($_POST["type"]) ? $_POST["type"]:"";
            $filename = isset($_POST["filename"]) ? $_POST["filename"]:"";
            $create_date = isset($_POST["create_date"]) ? $_POST["create_date"]:"";
            $location = getcwd();
            if($id >0){
                if($type=="apk"){
                    $path = $location."/upload/modgame/".$_SESSION['username']."/modapk/".date("Y/md",$create_date)."/".$filename;
                    $table = "c_attach_payment_apk";
                    $result = CommonDB::deleteRow($table,array("id"=>$id));
                }else if($type=="java"){
                    $path = $location."/upload/modgame/".$_SESSION['username']."/modjar/".date("Y/md",$create_date)."/".$filename;
                    $table = "c_attach_payment_jar";
                    $result = CommonDB::deleteRow($table,array("id"=>$id)); 
                }
                if($result >0){
                    unlink($path);
                    echo 1;exit();
                }else{
                    echo "Chưa thay đổi dữ liệu";
                }
            }
        }
    }
?>
